import { pathExists, readFile, writeFile } from 'fs-extra';
import { homedir } from 'os';
import { join } from 'path';

import c from '../colors';
import { runTask } from '../common';
import type { Config } from '../definitions';
import { extractTemplate } from '../util/template';

export async function addOhos(config: Config): Promise<void> {
  await runTask(`Adding native ohos project in ${c.strong(config.ohos.platformDir)}`, async () => {
    await extractTemplate(config.cli.assets.ohos.platformTemplateArchiveAbs, config.ohos.platformDirAbs);
    // 添加 SDK 路径检测和配置
    await createLocalProperties(config.ohos.platformDirAbs);
  });
}

export async function createLocalProperties(platformDir: string): Promise<void> {
  // 动态检测 HarmonyOS SDK 路径
  const detectedSdkPath = await detectOhosSdkPath();
  
  if (detectedSdkPath) {
    const localPropertiesPath = join(platformDir, 'local.properties');
    
    try {
      // 尝试读取现有的 local.properties 文件
      let content = await readFile(localPropertiesPath, 'utf-8');
      // 替换模板变量
      content = content.replace('{{OHOS_SDK_PATH}}', detectedSdkPath);
      await writeFile(localPropertiesPath, content, { encoding: 'utf-8' });
    } catch (error) {
      // 如果文件不存在，创建新的 local.properties
      const localSettings = `# HarmonyOS SDK location
# This file is automatically generated by Capacitor.
# Do not modify this file -- YOUR CHANGES WILL BE ERASED!
hwsdk.dir=${detectedSdkPath}
`;
      await writeFile(localPropertiesPath, localSettings, { encoding: 'utf-8' });
    }
  }
}

export async function createOhosProperties(platformDir: string): Promise<void> {
  // 创建鸿蒙项目的基本配置文件
  const ohPackageConfig = {
    "name": "capacitor-ohos-app",
    "version": "1.0.0",
    "description": "Capacitor HarmonyOS Application",
    "main": "index.ets",
    "author": "",
    "license": "Apache-2.0",
    "dependencies": {}
  };

  await writeFile(join(platformDir, 'oh-package.json5'), JSON.stringify(ohPackageConfig, null, 2), {
    encoding: 'utf-8',
  });
}

async function detectOhosSdkPath(): Promise<string | null> {
  // 动态检测常见的 HarmonyOS SDK 安装路径
  const username = process.env.USERNAME || process.env.USER || 'user';
  const commonSdkPaths = [
    // 用户目录下的标准路径
    join(homedir(), 'Huawei', 'Sdk'),
    join(homedir(), 'OpenHarmony', 'Sdk'),
    join(homedir(), 'HarmonyOS', 'Sdk'),
    // 系统标准安装路径
    'C:\\Huawei\\Sdk',
    'D:\\Huawei\\Sdk',
    'C:\\OpenHarmony\\Sdk',
    'D:\\OpenHarmony\\Sdk',
    'C:\\HarmonyOS\\Sdk',
    'D:\\HarmonyOS\\Sdk',
    // 用户特定路径
    `C:\\Users\\${username}\\Huawei\\Sdk`,
    `C:\\Users\\${username}\\OpenHarmony\\Sdk`,
    `C:\\Users\\${username}\\HarmonyOS\\Sdk`,
    // DevEco Studio 默认路径
    join(homedir(), 'AppData', 'Local', 'Huawei', 'Sdk'),
    'C:\\Program Files\\Huawei\\Sdk',
    'D:\\Program Files\\Huawei\\Sdk',
  ];

  for (const sdkPath of commonSdkPaths) {
    if (await pathExists(sdkPath)) {
      // 验证这是一个有效的 HarmonyOS SDK 目录
      const apiPath = join(sdkPath, 'openharmony');
      const toolchainsPath = join(sdkPath, 'toolchains');
      
      if (await pathExists(apiPath) || await pathExists(toolchainsPath)) {
        return sdkPath;
      }
    }
  }

  return null;
}